<template>
  <div class="bucket-monitor">
    <el-row :gutter="20" type="flex" justify="start" align="middle" style="gap: 10px;">
      <el-col :span="7">
        <date-range-picker
            :start-date="startDate"
            :end-date="endDate"
            @update:startDate="startDate = $event"
            @update:endDate="endDate = $event"
            style="width: 350px;"
        />
      </el-col>
      <el-col :span="9">
        <el-button style="margin-left: 15px;" type="primary"  @click="filterData">筛选</el-button>
        <el-button id="reset-button" type="default"  @click="resetFilter" >重置</el-button>
      </el-col>
    </el-row>
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <bucket-chart :chart-data="bucketChartData" :x-axis="timeAxis"/>
      </el-col>
    </el-row>
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <data-table
            :filtered-data="filteredData"
            :current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            :total-pages="totalPages"
            @current-change="handleCurrentChange"
        />
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {getRecentChartData, getRecentTableData, getFilteredChartData, getFilteredTableData} from '@/api/dataService';
import BucketChart from '@/components/Chart/BucketChart.vue';
import DataTable from '@/components/Table/DataTable.vue';
import DateRangePicker from '@/components/DateRangePicker/DateRangePicker.vue';

export default {
  name: 'BucketMonitor',
  components: {
    BucketChart,
    DataTable,
    DateRangePicker
  },
  data() {
    return {
      startDate: '',
      endDate: '',
      currentPage: 1,
      pageSize: 6,
      total: 0,
      totalPages: 1,
      allTableData: [],
      filteredTableData: [],
      bucketChartData: [],
      timeAxis: this.generateTimeAxis(),
      isFiltering: false
    };
  },
  computed: {
    filteredData() {
      return this.filteredTableData;
    }
  },
  methods: {
    generateTimeAxis() {
      const now = new Date();
      const times = [];
      for (let i = 60; i >= 0; i--) {
        const time = new Date(now.getTime() - i * 30 * 1000); // 30秒一个点
        const hours = String(time.getHours()).padStart(2, '0');
        const minutes = String(time.getMinutes()).padStart(2, '0');
        const seconds = String(time.getSeconds()).padStart(2, '0');
        times.push(`${hours}:${minutes}:${seconds}`);
      }
      return times;
    },
    generateTimeAxisForFilteredData() {
      const startTime = new Date(this.startDate);
      const endTime = new Date(this.endDate);
      const timeInterval = (endTime - startTime) / 60;
      const times = [];
      for (let i = 0; i <= 60; i++) {
        const time = new Date(startTime.getTime() + i * timeInterval);
        const year = time.getFullYear();
        const month = String(time.getMonth() + 1).padStart(2, '0');
        const day = String(time.getDate()).padStart(2, '0');
        const hours = String(time.getHours()).padStart(2, '0');
        const minutes = String(time.getMinutes()).padStart(2, '0');
        const seconds = String(time.getSeconds()).padStart(2, '0');
        times.push(`${year}-${month}-${day} ${hours}:${minutes}:${seconds}`);
      }
      this.timeAxis = times;
    },
    async fetchTableData(page = 1) {
      try {
        const tableResponse = await getRecentTableData(page, this.pageSize, '5TES1702MM1');
        const tableData = tableResponse.data.records;
        this.allTableData = tableData;
        this.total = tableResponse.data.total;
        this.totalPages = tableResponse.data.pages;
        if (tableResponse.data.pages === 0) {
          this.totalPages = 1;
        }
        this.currentPage = tableResponse.data.current;
        this.processTableData(tableData);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    },
    async fetchChartData() {
      try {
        const chartResponse = await getRecentChartData('5TES1702MM1');
        const bucketData = this.processChartData(chartResponse.data);
        this.bucketChartData = this.fillMissingDataPoints(bucketData);
      } catch (error) {
        console.error('Error fetching chart data:', error);
      }
    },
    processChartData(data) {
      return data.map(item => {
        const time = item.createTime.split(' ')[1]; // 获取时间部分
        return {
          time: time, // 保留到秒级别
          value: item.measureValue,
        };
      });
    },
    processTableData(data) {
      const processedData = data.map(item => {
        return {
          seq: item.serialNumber,
          time: item.createTime.split(' ')[1], // 保留时间部分
          sensor: item.sensorName,
          value: item.measureValue
        };
      });
      this.filteredTableData = processedData;
    },
    fillMissingDataPoints(data) {
      const timeAxis = this.generateTimeAxis();
      const dataMap = new Map(data.map(item => [item.time, item.value]));
      return timeAxis.map(time => {
        let value = dataMap.get(time);
        if (value === undefined && data.length > 0) {
          // 获取与当前时间点最近的时间点
          const closestData = data.reduce((prev, curr) => {
            const prevTimeDiff = Math.abs(this.timeToSeconds(prev.time) - this.timeToSeconds(time));
            const currTimeDiff = Math.abs(this.timeToSeconds(curr.time) - this.timeToSeconds(time));
            return (currTimeDiff < prevTimeDiff) ? curr : prev;
          }, data[0]);
          value = closestData ? closestData.value : undefined;
        }
        return {time, value};
      });
    },
    timeToSeconds(timeStr) {
      const [hours, minutes, seconds] = timeStr.split(':').map(Number);
      return hours * 3600 + minutes * 60 + seconds;
    },
    async filterData() {
      if (!this.validateDateRange()) {
        return;
      }
      this.isFiltering = true;
      this.generateTimeAxisForFilteredData();
      await this.fetchFilteredChartData();
      await this.fetchFilteredTableData();
    },
    async fetchFilteredChartData() {
      try {
        const chartResponse = await getFilteredChartData(this.startDate, this.endDate, '5TES1702MM1');
        const bucketData = this.processChartData(chartResponse.data);
        this.bucketChartData = this.fillMissingDataPoints(bucketData);
      } catch (error) {
        console.error('Error fetching filtered chart data:', error);
      }
    },
    async fetchFilteredTableData(page = 1) {
      try {
        const response = await getFilteredTableData(this.startDate, this.endDate, page, this.pageSize, '5TES1702MM1');
        const tableData = response.data.records;
        this.processTableData(tableData);
        this.total = response.data.total;
        this.totalPages = response.data.pages;
        this.currentPage = page;
      } catch (error) {
        console.error('Error fetching filtered table data:', error);
      }
    },
    resetFilter() {
      this.startDate = '';
      this.endDate = '';
      this.isFiltering = false;
      this.fetchTableData(this.currentPage);
      this.timeAxis = this.generateTimeAxis();
      this.fetchChartData();
    },
    handleCurrentChange(page) {
      if (page > 0 && page <= this.totalPages) {
        this.currentPage = page;
        if (this.isFiltering) {
          this.fetchFilteredTableData(this.currentPage);
        } else {
          this.fetchTableData(this.currentPage);
        }
      }
    },
    validateDateRange() {
      if (!this.startDate || !this.endDate) {
        return false;
      }
      if (!(new Date(this.startDate) <= new Date(this.endDate))) {
        return false;
      }
      return true;
    }
  },
  mounted() {
    this.fetchTableData().then(() => {
      this.$nextTick(() => {
        this.timeAxis = this.generateTimeAxis();
      });
    });
    this.fetchChartData().then(() => {
      this.$nextTick(() => {
        this.timeAxis = this.generateTimeAxis();
      });
    });
    this.interval = setInterval(() => {
      if (!this.isFiltering) {
        this.fetchTableData();
        this.fetchChartData().then(() => {
          this.$nextTick(() => {
            this.timeAxis = this.generateTimeAxis();
          });
        });
      }
    }, 30000);
  },
  beforeUnmount() {
    clearInterval(this.interval);
  }
};
</script>

<style scoped lang="scss">
.bucket-monitor {
  padding: 20px;
}

/* 筛选-重置按钮 */
.el-button {
  @include button-style;
}

#reset-button {
  @include reset-style
}

/* 修改“开始时间”“结束时间”的占位符颜色 */
:deep(.el-date-editor .el-range-input ) {
  color: white;
}


:deep(.el-date-editor .el-range-separator ) {
  color: rgb(189, 189, 189);
}
</style>
